package com.netkit;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.FrameDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.netkit.message.Message;

public class NetkitProtocolDecoder extends FrameDecoder {
	private static int a=0;
	
	Logger logger = LoggerFactory.getLogger(NetkitProtocolDecoder.class);
	public NetkitProtocolDecoder() {
	}
	
	protected Object decode(ChannelHandlerContext context, Channel channel, ChannelBuffer source)throws Exception{	
		if(source.readableBytes() < 8){
			return null;
		}
		
		source.markReaderIndex();
		
		try{
			int messageId = source.readInt();
			
			int contentLen = source.readInt();
	
			if(source.readableBytes() < contentLen){
				logger.error("source.readableBytes() < contentLen");
				source.resetReaderIndex();
				return null;
			}
			
			byte[] data = new byte[contentLen];
			source.readBytes(data);
			if(messageId==61002){
				a++;
				if(a%1000==0){
					logger.info("recive number:"+a);
				}
				
			}
			
			return new Message(messageId,data);
		}catch(Exception e){
			source.resetReaderIndex();
		}
		
		return null;
	}
	
	
}
